<script setup lang="ts">
import {findAll} from "@/api/accessory";

/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "BillSummary",
  inheritAttrs: false,
});
import {
  getBillSummaryPage,
  testGenerateBillSummary,
	exportCertificate
} from "@/api/billSummary";

import { BillSummaryQuery, BillSummaryPageVO } from "@/api/billSummary/types";
import lodash from "lodash-es";
import {AccessoryList} from "@/api/accessory/types";
import {ElLoading} from "element-plus";
import {StoreForm} from "@/api/store/types";
import {listAll} from "@/api/store";

const queryFormRef = ref(ElForm); // 查询表单

const loading = ref(false);
const ids = ref([]);
const total = ref(0);
const monthValue = ref('')
const createMonthValue = ref('')
const storeList = ref<StoreForm[]>();
const accessoryList = reactive<AccessoryList>({
	value: []
});

const queryParams = reactive<BillSummaryQuery>({
	billMonth: '',
	keywords: '',
	pageNum: 1,
	pageSize: 20,
});
const exportParams = reactive<BillSummaryQuery>({
	billMonth: '',
	keywords: '',
	pageNum: 1,
	pageSize: 10,
});
const createParams = reactive<BillSummaryQuery>({
	billMonth: '',
	pageNum: 1,
	pageSize: 20,
});

const billSummaryList = ref<BillSummaryPageVO[]>();
const tableList = ref<[]>();
const pageMap:Map<number, any> = new Map();
const dialog = reactive<DialogOption>({
	visible: false,
});

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
async function openDialog() {
	dialog.visible = true;
	dialog.title = "选择会计周期";
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
}

/**
 * 查询
 */
function handleQuery() {
  queryParams.billMonth = monthValue.value
  loading.value = true;
  getBillSummaryPage(queryParams)
    .then(({ data }) => {
      billSummaryList.value = data.list;
		if (billSummaryList.value !== undefined && billSummaryList.value.length > 0) {
			for (const bill of billSummaryList.value) {
				const accessory = lodash.get(bill, 'accessory')
				if (accessory !== null && accessory !== undefined) {
					for (let key of Object.keys(accessory)) {
						lodash.set(bill, key, lodash.get(accessory, key))
					}
				}
			}
		}
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 分页
function pageHandle() {
	pageData()
}

function pageData() {
	let page = 1
	let count = 0
	let dataList = []
	if (billSummaryList.value !== undefined) {
		for (let data of billSummaryList.value) {
			dataList.push(data)
			count += 1
			if (count === queryParams.pageSize) {
				count = 0
				pageMap.set(page, dataList)
				dataList = JSON.parse(JSON.stringify([]))
				page += 1
			}
		}
		// 如果有余数，把剩下的数据添加到最后一页
		if (billSummaryList.value.length % queryParams.pageSize !== 0) {
			if (page === 1) {
				pageMap.set(page, dataList)
			}else{
				pageMap.set(page + 1, dataList)
			}
		}
	}
	tableList.value = pageMap.get(queryParams.pageNum)
}

/** 重置查询 */
function resetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}

function getAllAccessory(){
	accessoryList.value = []
	findAll().then((response) => {
		if (response.data !== null && response.data.length > 0) {
			const head = lodash.head(response.data)
			for (const key of Object.keys(head)) {
				if (key.includes('Name') && lodash.get(head, key) !== null && lodash.get(head, key) !== undefined && lodash.get(head, key) !== '') {
					accessoryList.value.push(lodash.get(head, key))
				}
			}
		}
	})
}

function handleSubmit() {
	const importLoading = ElLoading.service({
		lock: true,
		text: '生成中...',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	createParams.billMonth = createMonthValue.value
	testGenerateBillSummary(createParams).then((response) => {
		ElMessage.success('生成完成');
		closeDialog();
	}).finally(() => {
		importLoading.close()
	});
}
/**
 * 获取所有店铺
 */
function getAllStore() {
	listAll().then((response) => {
		storeList.value = response.data;
	});
}

/** 导出凭证 */
function handleCertificateExport() {
	exportParams.billMonth = monthValue.value
	exportCertificate(exportParams).then((response: any) => {
		const blob = new Blob([response.data], {
			type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
		});
		const a = document.createElement("a");
		const href = window.URL.createObjectURL(blob); // 下载的链接
		a.href = href;
		a.download = decodeURI(
			response.headers["content-disposition"].split(";")[1].split("=")[1]
		); // 获取后台设置的文件名称
		document.body.appendChild(a);
		a.click(); // 点击导出
		document.body.removeChild(a); // 下载完成移除元素
		window.URL.revokeObjectURL(href); // 释放掉blob对象
	});
}

onMounted(() => {
  let now = new Date()
  now.setMonth(now.getMonth() - 1)
  let month = now.getMonth()
  if (month < 9){
	  monthValue.value = now.getFullYear() + '0' + (now.getMonth() + 1) + ''
	  createMonthValue.value = now.getFullYear() + '0' + (now.getMonth() + 1) + ''
  }	else {
	  monthValue.value = now.getFullYear() + '' + (now.getMonth() + 1) + ''
	  createMonthValue.value = now.getFullYear() + '' + (now.getMonth() + 1) + ''
  }
  handleQuery(); // 初始化标准账单配置列表数据
  getAllAccessory()  // 查询所有辅助项
	getAllStore()
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col>
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="会计期间" prop="keywords">
							<el-date-picker
									v-model="monthValue"
									type="month"
									value-format="YYYYMM"
									:editable="false"
									:clearable="false"
									placeholder="选择会计期间"
							/>
            </el-form-item>
			  <el-form-item label="统一账单汇总ID" prop="keywords">
				  <el-input
						  v-model="queryParams.keywords"
						  placeholder="请输入统一账单汇总ID"
						  clearable
						  style="width: 200px"
						  @keyup.enter="handleQuery"
				  />
			  </el-form-item>
			  <el-form-item label="电商平台店铺名称" prop="shopCode">
					<el-select
							v-model="queryParams.shopCode"
							placeholder="全部"
							clearable
							class="yz-el-select"
					>
						<el-option
								v-for="item in storeList"
								:key="item.commercePlatformStoreCode"
								:label="item.commercePlatformStoreName"
								:value="item.commercePlatformStoreCode"
						/>
					</el-select>
			  </el-form-item>
			  <el-form-item label="记账项目" prop="billProject">
				  <el-input
						  v-model="queryParams.billProject"
						  placeholder="请输入记账项目"
						  clearable
						  style="width: 200px"
						  @keyup.enter="handleQuery"
				  />
			  </el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery"
						><i-ep-search />搜索</el-button>
				</el-form-item>
			  <el-form-item>
				  <el-button type="primary" @click="openDialog"
				  >账单汇总</el-button>
			  </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
					<template #header>
						<div class="flex justify-between">
							<div>
							</div>
							<div>
								<el-button class="ml-3" @click="handleCertificateExport" v-hasPerm="['sys:billSummary:export']"
								><template #icon><i-ep-download /></template>凭证生成</el-button>
							</div>
						</div>
					</template>
          <el-table
            v-loading="loading"
            :data="billSummaryList"
						size="small"
						:header-row-style="{color: 'dimgray'}"
						border
						:height="billSummaryList && billSummaryList.length > 0 ? 580 : 130"
          >
			  <el-table-column
					  label="统一账单汇总ID"
					  width="80"
					  align="center" show-overflow-tooltip
					  prop="sysBillId"
			  />
			  <el-table-column
					  label="对账系统平台名称"
					  width="80"
					  align="center" show-overflow-tooltip
					  prop="channel"
			  />
			  <el-table-column
					  label="电商平台店铺名称"
					  width="80"
					  align="center" show-overflow-tooltip
					  prop="shopName"
			  />
			  <el-table-column
					  label="会计期间"
					  width="140"
					  align="center" show-overflow-tooltip
					  prop="billDate"
			  />
			  <el-table-column
					  label="记账项目"
					  align="center" show-overflow-tooltip
					  prop="billProject"
					  width="200"
			  ></el-table-column>
			  <el-table-column
					  label="账单金额"
					  align="center" show-overflow-tooltip
					  width="90"
					  prop="billAmount"
			  ></el-table-column>
			  <el-table-column
					  label="不含税金额"
					  align="center" show-overflow-tooltip
					  prop="unTaxAmount"
					  width="90"
			  ></el-table-column>
			  <el-table-column
					  label="税额"
					  align="center" show-overflow-tooltip
					  prop="taxAmount"
					  width="90"
			  ></el-table-column>
			  <el-table-column
					  label="入账主体"
					  align="center" show-overflow-tooltip
					  prop="receiveCompany"
					  width="80"
			  ></el-table-column>
			  <el-table-column
					  label="是否分摊"
					  align="center" show-overflow-tooltip
					  prop="apportionment"
					  width="80"
			  ></el-table-column>
			  <el-table-column
					  label="票前票后"
					  align="center" show-overflow-tooltip
					  prop="invoice"
					  width="80"
			  ></el-table-column>
			  <el-table-column
					  label="末级科目编码"
					  align="center" show-overflow-tooltip
					  prop="lastCode"
					  width="100"
			  ></el-table-column>
			  <el-table-column
					  label="末级科目名称"
					  align="center" show-overflow-tooltip
					  prop="lastName"
					  width="100"
			  ></el-table-column>
			  <el-table-column
					  label="稽核标识"
					  align="center" show-overflow-tooltip
					  prop="audit"
					  width="80"
			  ></el-table-column>
			  <el-table-column
					  label="是否参与记账"
					  align="center" show-overflow-tooltip
					  prop="accounting"
					  width="90"
			  ></el-table-column>
			  <el-table-column
					  label="供应商名称"
					  align="center" show-overflow-tooltip
					  prop="carrier"
					  width="80"
			  ></el-table-column>
			  <el-table-column
					  v-for="accessory in accessoryList.value"
					  :label="accessory"
					  width="90"
					  align="center" show-overflow-tooltip
					  :prop="accessory"
			  />
          </el-table>

          <pagination
			v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
	  <el-dialog
			  v-model="dialog.visible"
			  :title="dialog.title"
			  width="500px"
			  :close-on-click-modal="false"
			  @close="closeDialog"
	  >
		  <el-form
				  ref="dataFormRef"
				  label-width="150px"
		  >
			  <el-date-picker
					  v-model="createMonthValue"
					  type="month"
					  value-format="YYYYMM"
					  :editable="false"
					  :clearable="false"
					  placeholder="选择会计周期"
			  />
		  </el-form>
		  <template #footer>
			  <div class="dialog-footer">
				  <el-button type="primary" @click="handleSubmit">确 定</el-button>
				  <el-button @click="closeDialog">取 消</el-button>
			  </div>
		  </template>
	  </el-dialog>

  </div>
</template>
